package api

import (
	"net/http"
	"strconv"

	"gitee.com/war2001/NiuMaEasyGo/model"
	"gitee.com/war2001/NiuMaEasyGo/nm_core/router"
	"gitee.com/war2001/NiuMaEasyGo/utils"
	"github.com/gin-gonic/gin"
)

// WechatConfigController 微信配置控制器
type WechatConfigController struct {
	configService model.WechatConfigService
	wechatUtil    *utils.WechatUtil
}

// NewWechatConfigController 创建微信配置控制器
func NewWechatConfigController(configService model.WechatConfigService, wechatUtil *utils.WechatUtil) *WechatConfigController {
	return &WechatConfigController{
		configService: configService,
		wechatUtil:    wechatUtil,
	}
}

// Create 创建微信配置
func (c *WechatConfigController) Create(ctx *gin.Context) {
	var config model.WechatConfig
	if err := ctx.ShouldBindJSON(&config); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "参数错误: " + err.Error()})
		return
	}

	// 从上下文中获取当前租户ID
	tenantID, exists := ctx.Get("tenant_id")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未获取到商户信息"})
		return
	}
	config.TenantID = tenantID.(uint)

	if err := c.configService.Create(&config); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "创建失败: " + err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "创建成功",
		"data": config,
	})
}

// Update 更新微信配置
func (c *WechatConfigController) Update(ctx *gin.Context) {
	id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "ID参数错误"})
		return
	}

	// 获取原配置
	config, err := c.configService.GetByID(uint(id))
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "配置不存在: " + err.Error()})
		return
	}

	// 从上下文中获取当前租户ID
	tenantID, exists := ctx.Get("tenant_id")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未获取到商户信息"})
		return
	}

	// 验证是否属于当前租户
	if config.TenantID != tenantID.(uint) {
		ctx.JSON(http.StatusForbidden, gin.H{"error": "无权操作此配置"})
		return
	}

	// 绑定新数据
	if err := ctx.ShouldBindJSON(config); err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "参数错误: " + err.Error()})
		return
	}

	// 确保ID和TenantID不变
	config.ID = uint(id)
	config.TenantID = tenantID.(uint)

	if err := c.configService.Update(config); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "更新失败: " + err.Error()})
		return
	}

	// 清除缓存
	c.wechatUtil.ClearCache(config.ID)

	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "更新成功",
		"data": config,
	})
}

// Delete 删除微信配置
func (c *WechatConfigController) Delete(ctx *gin.Context) {
	id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "ID参数错误"})
		return
	}

	// 获取配置
	config, err := c.configService.GetByID(uint(id))
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "配置不存在: " + err.Error()})
		return
	}

	// 从上下文中获取当前租户ID
	tenantID, exists := ctx.Get("tenant_id")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未获取到商户信息"})
		return
	}

	// 验证是否属于当前租户
	if config.TenantID != tenantID.(uint) {
		ctx.JSON(http.StatusForbidden, gin.H{"error": "无权操作此配置"})
		return
	}

	if err := c.configService.Delete(uint(id)); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "删除失败: " + err.Error()})
		return
	}

	// 清除缓存
	c.wechatUtil.ClearCache(uint(id))

	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "删除成功",
	})
}

// GetByID 根据ID获取微信配置
func (c *WechatConfigController) GetByID(ctx *gin.Context) {
	id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "ID参数错误"})
		return
	}

	// 获取配置
	config, err := c.configService.GetByID(uint(id))
	if err != nil {
		ctx.JSON(http.StatusNotFound, gin.H{"error": "配置不存在: " + err.Error()})
		return
	}

	// 从上下文中获取当前租户ID
	tenantID, exists := ctx.Get("tenant_id")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未获取到商户信息"})
		return
	}

	// 验证是否属于当前租户
	if config.TenantID != tenantID.(uint) {
		ctx.JSON(http.StatusForbidden, gin.H{"error": "无权查看此配置"})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "获取成功",
		"data": config,
	})
}

// List 获取当前租户的所有微信配置
func (c *WechatConfigController) List(ctx *gin.Context) {
	// 从上下文中获取当前租户ID
	tenantID, exists := ctx.Get("tenant_id")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未获取到商户信息"})
		return
	}

	configs, err := c.configService.ListByTenant(tenantID.(uint))
	if err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "获取失败: " + err.Error()})
		return
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "获取成功",
		"data": configs,
	})
}

// SetDefault 设置默认微信配置
func (c *WechatConfigController) SetDefault(ctx *gin.Context) {
	id, err := strconv.ParseUint(ctx.Param("id"), 10, 32)
	if err != nil {
		ctx.JSON(http.StatusBadRequest, gin.H{"error": "ID参数错误"})
		return
	}

	// 从上下文中获取当前租户ID
	tenantID, exists := ctx.Get("tenant_id")
	if !exists {
		ctx.JSON(http.StatusUnauthorized, gin.H{"error": "未获取到商户信息"})
		return
	}

	if err := c.configService.SetDefault(uint(id), tenantID.(uint)); err != nil {
		ctx.JSON(http.StatusInternalServerError, gin.H{"error": "设置失败: " + err.Error()})
		return
	}

	// 清除所有缓存，因为默认配置已更改
	c.wechatUtil.ClearAllCache()

	ctx.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "设置成功",
	})
}

// RegisterRoutes 注册路由 (旧方式，保留用于兼容)
func (c *WechatConfigController) RegisterRoutes(router *gin.RouterGroup) {
	wechatGroup := router.Group("/wechat/config")
	{
		wechatGroup.POST("", c.Create)
		wechatGroup.PUT("/:id", c.Update)
		wechatGroup.DELETE("/:id", c.Delete)
		wechatGroup.GET("/:id", c.GetByID)
		wechatGroup.GET("", c.List)
		wechatGroup.PUT("/:id/default", c.SetDefault)
	}
}

// CreateMetadata 创建微信配置元数据
func (c *WechatConfigController) CreateMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "新增配置",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "wechat:config:add",
		ParentPath:   "/wechat/config",
		MenuType:     "button",
		MenuCategory: "tenant",
		Method:       "POST",
		APIPath:      "",
		RequireAuth:  true,
		OrderNum:     1,
	}
}

// UpdateMetadata 更新微信配置元数据
func (c *WechatConfigController) UpdateMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "编辑配置",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "wechat:config:edit",
		ParentPath:   "/wechat/config",
		MenuType:     "button",
		MenuCategory: "tenant",
		Method:       "PUT",
		APIPath:      "/:id",
		RequireAuth:  true,
		OrderNum:     2,
	}
}

// DeleteMetadata 删除微信配置元数据
func (c *WechatConfigController) DeleteMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "删除配置",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "wechat:config:delete",
		ParentPath:   "/wechat/config",
		MenuType:     "button",
		MenuCategory: "tenant",
		Method:       "DELETE",
		APIPath:      "/:id",
		RequireAuth:  true,
		OrderNum:     3,
	}
}

// GetByIDMetadata 获取微信配置详情元数据
func (c *WechatConfigController) GetByIDMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "配置详情",
		Path:         "/wechat/config/detail",
		Component:    "/wechat/config/detail",
		Icon:         "",
		Permission:   "wechat:config:query",
		ParentPath:   "/wechat/config",
		MenuType:     "menu",
		MenuCategory: "tenant",
		Method:       "GET",
		APIPath:      "/:id",
		RequireAuth:  true,
		Hidden:       true,
		OrderNum:     1,
	}
}

// ListMetadata 获取微信配置列表元数据
func (c *WechatConfigController) ListMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "微信配置",
		Path:         "/wechat/config",
		Component:    "/wechat/config/index",
		Icon:         "wechat",
		Permission:   "wechat:config:list",
		ParentPath:   "/wechat",
		MenuType:     "menu",
		MenuCategory: "tenant",
		Method:       "GET",
		APIPath:      "",
		RequireAuth:  true,
		OrderNum:     1,
	}
}

// SetDefaultMetadata 设置默认微信配置元数据
func (c *WechatConfigController) SetDefaultMetadata() router.RouteMetadata {
	return router.RouteMetadata{
		Title:        "设为默认",
		Path:         "",
		Component:    "",
		Icon:         "",
		Permission:   "wechat:config:default",
		ParentPath:   "/wechat/config",
		MenuType:     "button",
		MenuCategory: "tenant",
		Method:       "PUT",
		APIPath:      "/:id/default",
		RequireAuth:  true,
		OrderNum:     4,
	}
}
